<template>
    <div class="nav">
        <!-- logo标题区域开始 -->
        <div style="width: 160px; display: flex; align-items: center; margin: 0 100px 0 0">
            <img style="width: 100%; height: 40px;" src="@/assets/imge/logo.png" alt="logo">
        </div>
        <!-- logo标题区域开始 -->

        <!-- 对应页面（主页/技术交流/协作开发）按钮区域开始 -->
        <div class="nav-box">
            <router-link to="/userhome" class="nav-option" :class="{ active: isActive('/userhome') }">主页</router-link>
            <router-link to="/bolg" class="nav-option" :class="{ active: isActive('/bolg') }">博客</router-link>
            <router-link to="/questionanswers" class="nav-option" :class="{ active: isActive('/questionanswers') }">问答</router-link>
            <router-link to="/essay" class="nav-option" :class="{ active: isActive('/essay') }">随记</router-link>
            <router-link to="/collaborativedev" class="nav-option" :class="{ active: isActive('/collaborativedev') }">协作开发</router-link>
        </div>
        <!-- 对应页面（主页/技术交流/协作开发）按钮区域结束 -->

        <!-- 全局搜索区域开始 -->
        <div class="nav-box" style="padding-left: 20px">
            <el-input :prefix-icon="Search" placeholder="请输入要搜索的内容"
                      v-model="searchContent"
                      clearable
                      style="width: 230px; margin: 0 10px"
                      size="default"
            />
            <el-button type="primary" @click="goToSearchPage" size="default">搜索</el-button>
        </div>
        <!-- 全局搜索区域开始 -->

        <!-- 创作中心及下拉框开始 -->
        <div class="nav-box" style="margin: 0 30px 0 20px">
            <el-dropdown> <!-- 点击开始创作，默认打开写文章 / 后续扩展打开创作者中心 -->
                <el-button type="primary">
                    开始创作<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu style="display: flex; align-items: center">
                        <div class="dropdownItem">
                            <el-dropdown-item @click="router.push('/contentcreate')">写博客</el-dropdown-item>
                        </div>
                        <div class="dropdownItem">
                            <el-dropdown-item @click="handleQuestionClick">提问</el-dropdown-item>
                        </div>
                        <div class="dropdownItem">
                            <el-dropdown-item @click="handleEssayClick">随记</el-dropdown-item>
                        </div>
                        <div class="dropdownItem">
                            <el-dropdown-item @click="router.push('/projectCreate')">创建项目</el-dropdown-item>
                        </div>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div >
        <!-- 创作中心及下拉框开始 -->

        <!-- 消息中心及下拉框开始 -->
        <div class="nav-box" style="margin-right: 30px" v-if="loginUser">
            <el-dropdown>
                <div class="nav-icon-container">
                    <el-icon :size="25" class="nav-icon"><BellFilled /></el-icon>
                    <span v-if="unreadCount > 0" class="notification-badge">{{ unreadCount }}</span>
<!--                    <span class="notification-badge">5</span>-->
                </div>
                <template #dropdown>
                    <el-dropdown-menu style="height: 200px; padding: 5px 10px">
                        <el-dropdown-item @click="router.push('/messagecenter/generalmessage')">
                            <div class="dropdown-item">
                                <div class="item-title">互动通知</div>
                                <div class="item-count" v-if="interactionUnread > 0">{{ interactionUnread }}</div>
                            </div>
                        </el-dropdown-item>
                        <el-dropdown-item @click="router.push('/messagecenter/privatemessage')">
                            <div class="dropdown-item">
                                <div class="item-title">私信</div>
                                <div class="item-count" v-if="privateUnread > 0">{{ privateUnread }}</div>
                            </div>
                        </el-dropdown-item>
                        <el-dropdown-item @click="router.push('/messagecenter/systemmessage')">
                            <div class="dropdown-item">
                                <div class="item-title">系统通知</div>
                                <div class="item-count" v-if="systemUnread > 0">{{ systemUnread }}</div>
                            </div>
                        </el-dropdown-item>
                        <el-dropdown-item divided>
                            <div class="item-all" @click="router.push('/messagecenter')">
                                查看全部通知
                            </div>
                        </el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
        <!-- 消息中心及下拉框开始 -->

        <!-- 头像区域开始 -->
        <div v-if="loginUser" style="display: flex; align-items: center; padding-right: 20px">

            <el-dropdown>
                <div style="display: flex; align-items: center">
                    <el-avatar shape="circle" :size="35" fit="cover" :src="url" @error="errorHandler">
                        <img
                                src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png"
                                alt="加载错误"/> <!--图片加载失败的回退行为-->
                    </el-avatar>  <!-- :fit="cover" : 当展示类型为图片的时候，设置图片如何适应容器 -->
                    <span style="margin-left: 5px; color: #1d1c1c">{{ user.username }}</span>
                </div>
                <template #dropdown>
                    <el-dropdown-menu  style="height: 110px; padding: 5px 10px">
                        <el-dropdown-item @click="router.push(`/personalhome/${user.user_id}`)">我的主页</el-dropdown-item>
                        <el-dropdown-item @click="router.push('/personalcenter')">个人中心</el-dropdown-item>
                        <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>
        <div v-else style="display: flex; align-items: center; padding: 0 20px 0 20px; margin: 0 30px 0 30px">
            <router-link to="/login" class="nav-btn">登录</router-link>
            <span> &nbsp;&nbsp;|&nbsp;&nbsp;</span>
            <router-link to="/register" class="nav-btn">注册</router-link>
        </div>
        <!--头像区域结束-->
    </div>

    <!-- 发布提问弹窗 -->
    <el-dialog v-model="state.dialogQuestion" style="width: 700px; min-height: 400px">
        <strong style="font-size: 22px; padding: 0 600px 10px 10px; border-bottom: 2px #f5f4f1 solid">提 问</strong>
        <!-- 内容区域 -->
        <div style="display: flex; align-items: center; margin-top: 20px">
            <!--标题-->
            <div>
                <el-avatar :src="url" :size="40" fit="cover" shape="square" @error="errorHandler">
                    <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt="加载错误"/> <!--图片加载失败的回退行为-->
                </el-avatar>
            </div>
            <textarea v-model="title" placeholder="提出你的问题..." spellcheck="false" maxlength="80" rows="1" class="title-input"></textarea>
        </div>
        <!-- 内容正文 -->
        <TextEditor ref="editorRef" @getContent="handleGetContent"/>
        <!-- 发布按钮及上传图片内容等区域 -->
        <div style="position: relative; min-height: 40px; min-width: 100px">
            <!--按钮-->
            <div style="display: flex; align-items: center; justify-content:space-between; position: absolute; left: 10px; width: 650px">
                <span style="cursor: pointer" @click="handleCategoryOpen"><img src="@/assets/icon_svg/分类.svg" alt="icon" style="width: 22px; height: 22px"></span>
                <el-button type="primary" @click="publish">发布问题</el-button>
            </div>
            <div class="category-tag" v-if="state.isCategoryOpen">
                <el-tag
                    v-for="(category, index) in categories"
                    :key="index"
                    :class="{ active: selectedCategory === category.categoryId }"
                    @click="selectedCategory = category.categoryId"
                >
                    {{ category.categoryName }}
                </el-tag>
            </div>
        </div>
    </el-dialog>

    <!-- 发布随记弹窗 -->
    <el-dialog v-model="state.dialogEssay">
        <strong style="font-size: 22px; padding: 0 520px 10px 10px; border-bottom: 2px #f5f4f1 solid">生 活 随 记</strong>
        <!-- 内容区域 -->
        <div style="display: flex; align-items: center; margin-top: 20px">
            <!--标题-->
            <div>
                <el-avatar :src="url" :size="40" fit="cover" shape="square" @error="errorHandler">
                    <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" alt="加载错误"/> <!--图片加载失败的回退行为-->
                </el-avatar>
            </div>
            <textarea v-model="title" placeholder="开始记录 友善交流..." spellcheck="false" maxlength="80" rows="1" class="title-input"></textarea>
        </div>
        <!-- 内容正文 -->
        <TextEditor ref="editorRef" @getContent="handleGetContent"/>
        <!-- 发布按钮及上传图片内容等区域 -->
        <div style="position: relative; min-height: 40px; min-width: 100px">
            <!--按钮-->
            <div style="display: flex; align-items: center; justify-content:space-between; position: absolute; left: 10px; width: 620px">
                <span style="cursor: pointer" @click="handleCategoryOpen"><img src="@/assets/icon_svg/分类.svg" alt="icon" style="width: 22px; height: 22px"></span>
                <el-button type="primary" @click="publish">发布</el-button>
            </div>
            <div class="category-tag" v-if="state.isCategoryOpen">
                <el-tag
                    v-for="(category, index) in categories"
                    :key="index"
                    :class="{ active: selectedCategory === category.categoryId }"
                    @click="selectedCategory = category.categoryId"
                >
                    {{ category.categoryName }}
                </el-tag>
            </div>
        </div>
    </el-dialog>
</template>

<script setup>
import {reactive, toRefs, ref, onMounted, onUnmounted} from "vue";
import router from "@/router/index.js";
import {ArrowDown, BellFilled, Search} from "@element-plus/icons-vue";
import {useRoute} from "vue-router";
import TextEditor from "@/components/TextEditor.vue";
import request from "@/utils/request.js";
import {ElMessage} from "element-plus";

//监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接
// window.onbeforeunload = function () {
//     this.$websocket.close();
// }


//获取本地存储中的用户信息
let user;
const loginUser = localStorage.getItem('code_user');
if (loginUser) {
    // 将拿到的Json数据转化为JavaScript对象
    user = JSON.parse(loginUser);
}

// 初始化变量
const notices = ref([]);  // 系统公告列表
const privateMessages = ref([]); // 私信列表
const interactions = ref([]); // 互动通知列表
const userId = ref(user?.user_id); // 当前用户 ID
// 消息相关
const interactionUnread = ref(interactions.value.length); // 互动通知未读数
const privateUnread = ref(privateMessages.value.length); // 私信未读数
const systemUnread = ref(notices.value.length);  // 系统公告未读数
const unreadCount = ref(interactionUnread.value + privateUnread.value + systemUnread.value);  // 未读消息总数


onMounted(() => {

});

onUnmounted(() => {

});


// 全局搜索事件
const searchContent = ref('')
const goToSearchPage = () => {
    if (searchContent.value.trim()) {
        router.push({
            name: 'Search',
            query: { q: searchContent.value }
        })
    }
}

// 初始化加载方法或数据
onMounted(() => {
    request.get('/api/cata/selectCateAll').then(res => {
        if (res.code === '200') {
            categories.value = res.data; // 缓存新数据
        } else {
            console.log("分类列表查询失败")
        }
    })
});

// 高亮显示设置：判断路径是否匹配
// 获取当前路由路径
const route = useRoute();
// 自定义前缀匹配函数
const isActive = (prefixPath) => {
    return route.path.startsWith(prefixPath); // 判断当前路径是否以目标前缀开头
};

// 数据
const data = reactive({

})

//登出逻辑
const logout = () => {
    //跳转至主页
    router.push('/login')
    //点击登出，清楚本地存储
    localStorage.removeItem('code_user');
    //页面刷新
    // location.reload();
}

// avatar头像行为
const state = reactive({
    url: user?.profile_photo_path || '', // 可选链操作符 ?.
    dialogQuestion: false,
    dialogEssay: false,
    isCategoryOpen: false,
})
const { url } = toRefs(state)
const errorHandler = () => true //图片加载失败的回退行为

// 内容类型判断
let contentType = '';
const editorRef = ref()
const title = ref('') // 标题
// 提问点击事件方法
const handleQuestionClick = () => {
    state.dialogQuestion = true
    state.isCategoryOpen = false
    selectedCategory.value = ''
    contentType = 'QUESTION'
}
// 随记常见点击事件方法
const handleEssayClick = () => {
    state.dialogEssay = true
    state.isCategoryOpen = false
    selectedCategory.value = ''
    contentType = 'ESSAY'
}

// 分类数据
const categories = ref([]); // 缓存所有分类信息
const selectedCategory = ref('');  // 选择的分类
const handleCategoryOpen = () => {  // 分类按钮
    state.isCategoryOpen = !state.isCategoryOpen;
    selectedCategory.value = ''
}
const publish = () => {  // 发布问题方法
    editorRef.value.exposeContent() // 获取编辑器内容
}

// 监听子组件的getContent事件
const handleGetContent = (content) => {
    // 收集所有表单数据
    const formData = {
        userId: user.user_id,
        title: title.value,
        content: content,
        contentType: contentType,
        categoryId: selectedCategory.value,
        tags: null
    }
    // 发送数据到后端
    submitToBackend(formData)
}
// 提交到后端的方法
const submitToBackend = async (data) => {
    try {
        request.post('/api/content/addContent', data).then(res => {
            if (res.code === '200') {
                ElMessage.success("发布成功")
                state.dialogQuestion = false
                location.reload()
            } else if (res.code === '500') {
                ElMessage.error(res.msg)
            } else {
                ElMessage.error('发布失败')
            }
        })
    } catch (error) {
        ElMessage.error('网络错误:', error)
    }
}

</script>

<style scoped>
.nav {
    display: flex;
    position: fixed;
    align-items: center;
    justify-content: center;
    top: 0;
    border-bottom: 1px solid #cccbc8;
    height: 60px;
    width: 100%;
    background-image: radial-gradient(transparent 1px, #fffefb 1px);
    background-size: 4px 4px;
    backdrop-filter: saturate(50%) blur(4px);
    z-index: 999;
}
/*导航栏按钮样式*/
.nav-btn {
    /*font-size: 17px;*/
    color: #333333;
}
.nav-btn:hover {
    /*font-size: 17px;*/
    color: #1677ff;
}
/*导航通用盒子样式*/
.nav-box {
    /*flex: 1;*/
    display: flex;
    align-items: center;
    justify-content: center;
    width: fit-content;  /*自适应*/
}

/*导航栏选项样式*/
.nav-option {
    height: 60px;
    min-width: 70px;
    text-align: center;
    padding-top: 20px;
    color: #333333;
    transition: color 0.3s ease;
}
.nav-option:hover {
    color: #1677ff;
    border-bottom: solid #1677ff 3px;
}

.active {
    color: #1677ff;
    border-bottom: solid #1677ff 3px;
}
/*导航栏图标样式*/
.nav-icon:hover {
    color: #1677ff;
}

/*下拉框组件样式*/
.el-dropdown {
    /*鼠标移入变手*/
    cursor: pointer;
    border: 0;
    border-radius: 5px;
}
.dropdownItem {
    flex: 1;
    display: flex;
    align-items: center;
}

/*el-tooltip工具提示组件样式：el-tooltip__trigger 通常是鼠标悬停、点击等操作时触发显示工具提示内容的元素。*/
.el-tooltip__trigger {
    outline: none;
}

.title-input {
    padding-top: 10px;
    padding-left: 20px;
    width: 90%;
    min-height: 60px;
    -webkit-box-flex: 0;
    -ms-flex: none;
    flex: none;
    margin: 0;
    font-size: 1.5rem;
    font-weight: 300;
    color: #000;
    border: none;
    outline: none;
    resize: none;
    overflow: hidden;
}

.category-tag {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin: 0 100px 0 30px;
    padding-top: 40px;
}

.category-tag .el-tag {
    padding: 5px 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    cursor: pointer;
    height: 30px;
    font-size: 14px;
}
.category-tag .el-tag.active {
    color: #fffefb;
    background-color: #1677ff;
}



.nav-icon-container {
    position: relative;
}

.notification-badge {
    position: absolute;
    top: -6px;
    right: -6px;
    background-color: #ff4d4f;
    color: white;
    border-radius: 50%;
    width: 16px;
    height: 16px;
    font-size: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.dropdown-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 15px;
}

.item-title {
    color: #303133;
}

.item-count {
    background-color: #ff4d4f;
    color: white;
    border-radius: 9px;
    padding: 0 6px;
    font-size: 12px;
}

.item-all {
    color: #409eff;
    text-align: center;
    cursor: pointer;
}
</style>